package cmd_handler

import (
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/dynamicpb"
	"xgame.go_server/comm/log"
	"xgame.go_server/model"
	"xgame.go_server/msg"
	"xgame.go_server/service"
)

// 初始化
func init() {
	handleFuncMap[int32(msg.E_MsgCode_Login_USER_LOGIN_CMD.Number())] = handleUserLoginCmd
}

// 用户登录指令处理器
func handleUserLoginCmd(ctx MyCmdCtx, pMsgObj *dynamicpb.Message) {
	if nil == ctx ||
		nil == pMsgObj {
		return
	}

	// 转型动态消息
	cmdObj := &msg.UserLoginCmd{}

	pMsgObj.Range(func(f protoreflect.FieldDescriptor, v protoreflect.Value) bool {
		cmdObj.ProtoReflect().Set(f, v)
		return true
	})

	log.Info(
		"收到用户登录消息! userName = %s, password = %s",
		cmdObj.GetUserName(),
		cmdObj.GetPassword(),
	)

	// 根据用户名密码登录
	asyncBizResult := service.GetLoginService().LoginByPasswordAsync(
		cmdObj.GetUserName(),
		cmdObj.GetPassword(),
		ctx.GetClientIpAddr(),
	)

	asyncBizResult.OnComplete(func() {
		loginResult := asyncBizResult.GetReturnedObj()

		if nil == loginResult {
			return
		}

		user := loginResult.User

		result := &msg.UserLoginResult{
			UserId:     uint64(user.UserId),
			UserName:   user.UserName,
			HeroAvatar: user.HeroAvatar,
		}

		// 绑定用户 Id
		ctx.BindUserId(user.UserId)
		// 写出结果
		ctx.Write(result)

		// 添加到用户分组
		model.GetUserGroup().Add(user)
	})
}
